import logger from '../utils/logger.js'
/**
 * GOC 性能优化工具
 * 提供内存管理、动画帧率控制、大代码执行优化等功能
 */
class GocPerformance {
  constructor() {
    this.animationFrameId = null
    this.isAnimating = false
    this.frameRate = 60 // 目标帧率
    this.lastFrameTime = 0
    this.frameInterval = 1000 / this.frameRate
    
    // 内存管理
    this.memoryThreshold = 50 * 1024 * 1024 // 50MB
    this.gcInterval = 30000 // 30秒
    this.lastGcTime = 0
    
    // 执行优化
    this.batchSize = 100 // 批处理大小
    this.yieldInterval = 5 // 每5ms让出控制权
  }

  /**
   * 优化的动画循环
   * @param {Function} callback - 动画回调函数
   * @param {number} targetFPS - 目标帧率
   */
  optimizedAnimationLoop(callback, targetFPS = 60) {
    if (this.isAnimating) return

    this.isAnimating = true
    this.frameRate = targetFPS
    this.frameInterval = 1000 / this.frameRate

    const animate = (currentTime) => {
      if (!this.isAnimating) return

      const deltaTime = currentTime - this.lastFrameTime
      
      if (deltaTime >= this.frameInterval) {
        try {
          callback(deltaTime)
          this.lastFrameTime = currentTime
        } catch (error) {
          logger.error('Animation error:', error)
          this.stopAnimation()
        }
      }

      this.animationFrameId = requestAnimationFrame(animate)
    }

    this.animationFrameId = requestAnimationFrame(animate)
  }

  /**
   * 停止动画循环
   */
  stopAnimation() {
    this.isAnimating = false
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId)
      this.animationFrameId = null
    }
  }

  /**
   * 分块执行大代码
   * @param {Array} tasks - 任务数组
   * @param {Function} processor - 处理函数
   * @param {Function} onProgress - 进度回调
   * @returns {Promise} 执行结果
   */
  async executeInBatches(tasks, processor, onProgress) {
    const results = []
    const total = tasks.length
    
    for (let i = 0; i < total; i += this.batchSize) {
      const batch = tasks.slice(i, i + this.batchSize)
      
      // 处理当前批次
      const batchResults = await this.processBatch(batch, processor)
      results.push(...batchResults)
      
      // 报告进度
      if (onProgress) {
        onProgress(Math.min(i + this.batchSize, total), total)
      }
      
      // 让出控制权，避免阻塞UI
      await this.yield()
    }
    
    return results
  }

  /**
   * 处理单个批次
   * @param {Array} batch - 批次数据
   * @param {Function} processor - 处理函数
   * @returns {Promise} 处理结果
   */
  async processBatch(batch, processor) {
    const results = []
    
    for (const item of batch) {
      try {
        const result = await processor(item)
        results.push(result)
      } catch (error) {
        logger.error('Batch processing error:', error)
        results.push(null)
      }
    }
    
    return results
  }

  /**
   * 让出控制权
   * @returns {Promise}
   */
  yield() {
    return new Promise(resolve => {
      setTimeout(resolve, this.yieldInterval)
    })
  }

  /**
   * 内存管理
   */
  manageMemory() {
    const currentTime = Date.now()
    
    // 定期垃圾回收
    if (currentTime - this.lastGcTime > this.gcInterval) {
      this.forceGarbageCollection()
      this.lastGcTime = currentTime
    }
    
    // 检查内存使用
    if (performance.memory) {
      const usedMemory = performance.memory.usedJSHeapSize
      if (usedMemory > this.memoryThreshold) {
        logger.warn('High memory usage detected:', usedMemory)
        this.forceGarbageCollection()
      }
    }
  }

  /**
   * 强制垃圾回收（如果可用）
   */
  forceGarbageCollection() {
    if (window.gc && typeof window.gc === 'function') {
      window.gc()
    }
  }

  /**
   * 优化Canvas操作
   * @param {CanvasRenderingContext2D} ctx - Canvas上下文
   * @param {Array} operations - 绘制操作数组
   */
  optimizeCanvasOperations(ctx, operations) {
    // 按类型分组操作
    const groupedOps = this.groupOperationsByType(operations)
    
    // 批量执行相同类型的操作
    for (const [type, ops] of Object.entries(groupedOps)) {
      this.executeCanvasBatch(ctx, type, ops)
    }
  }

  /**
   * 按类型分组操作
   * @param {Array} operations - 操作数组
   * @returns {Object} 分组后的操作
   */
  groupOperationsByType(operations) {
    const groups = {}
    
    operations.forEach(op => {
      if (!groups[op.type]) {
        groups[op.type] = []
      }
      groups[op.type].push(op)
    })
    
    return groups
  }

  /**
   * 执行Canvas批次操作
   * @param {CanvasRenderingContext2D} ctx - Canvas上下文
   * @param {string} type - 操作类型
   * @param {Array} operations - 操作数组
   */
  executeCanvasBatch(ctx, type, operations) {
    ctx.save()
    
    switch (type) {
      case 'stroke':
        ctx.beginPath()
        operations.forEach(op => {
          ctx.moveTo(op.x1, op.y1)
          ctx.lineTo(op.x2, op.y2)
        })
        ctx.stroke()
        break
        
      case 'fill':
        operations.forEach(op => {
          ctx.fillStyle = op.color
          ctx.fillRect(op.x, op.y, op.width, op.height)
        })
        break
        
      case 'text':
        operations.forEach(op => {
          ctx.fillStyle = op.color
          ctx.font = op.font
          ctx.fillText(op.text, op.x, op.y)
        })
        break
    }
    
    ctx.restore()
  }

  /**
   * 防抖函数
   * @param {Function} func - 要防抖的函数
   * @param {number} delay - 延迟时间
   * @returns {Function} 防抖后的函数
   */
  debounce(func, delay) {
    let timeoutId
    return function (...args) {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => func.apply(this, args), delay)
    }
  }

  /**
   * 节流函数
   * @param {Function} func - 要节流的函数
   * @param {number} limit - 时间限制
   * @returns {Function} 节流后的函数
   */
  throttle(func, limit) {
    let inThrottle
    return function (...args) {
      if (!inThrottle) {
        func.apply(this, args)
        inThrottle = true
        setTimeout(() => inThrottle = false, limit)
      }
    }
  }

  /**
   * 获取性能指标
   * @returns {Object} 性能指标
   */
  getPerformanceMetrics() {
    const metrics = {
      frameRate: this.frameRate,
      isAnimating: this.isAnimating,
      batchSize: this.batchSize,
      yieldInterval: this.yieldInterval
    }

    if (performance.memory) {
      metrics.memory = {
        used: performance.memory.usedJSHeapSize,
        total: performance.memory.totalJSHeapSize,
        limit: performance.memory.jsHeapSizeLimit
      }
    }

    return metrics
  }

  /**
   * 清理资源
   */
  cleanup() {
    logger.log('🧹 [GocPerformance] 开始清理性能优化器...')
    try {
      this.stopAnimation()
      logger.log('✅ [GocPerformance] 动画停止完成')
    } catch (error) {
      logger.warn('⚠️ [GocPerformance] 停止动画时出错:', error)
    }
    
    try {
      this.forceGarbageCollection()
      logger.log('✅ [GocPerformance] 垃圾回收完成')
    } catch (error) {
      logger.warn('⚠️ [GocPerformance] 垃圾回收时出错:', error)
    }
    
    logger.log('✅ [GocPerformance] 性能优化器清理完成')
  }
}

// 导出性能优化工具
export default GocPerformance
